import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_hms_scan_kit/flutter_hms_scan_kit.dart';
import 'package:flutter_hms_scan_kit/scan_result.dart';
import 'package:flutter_hms_scan_kit/toast_utils.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_extend/share_extend.dart';
import 'package:toolbox/common/common.dart';
import 'package:toolbox/common/info.dart';
import 'package:toolbox/manager/tools.dart';

import '../../widgets/defaultDialog.dart';
import 'qr_state.dart';

class QrLogic extends GetxController {
  final QrState state = QrState();

  @override
  void onClose() {
    state.tabController.dispose();
    super.onClose();
  }

  void onTapScan() async {
    startScan();
  }

  Future<void> startScan() async {
    try {
      ScanResult? result = await FlutterHmsScanKit.scan;
      if (result == null) return;
      state.scanValue.value = result;
    } catch (e) {
      showToast(e.toString());
    }
  }

  createQrCode() async {
    if (state.controller.text.isEmpty) {
      showToast('输入框为空');
      return;
    }
    List<int>? bytes = await FlutterHmsScanKit.generateCode(
      content: state.controller.text,
      type: ScanTypeFormat.QRCODE_SCAN_TYPE,
      width: 500,
      height: 500,
      logo: state.logo?.readAsBytesSync(),
    );
    if (bytes == null) {
      showToast('生成失败');
      return;
    }
    Directory directory = await getTemporaryDirectory();
    File file = File('${directory.path}/ToolBoxQrCode${DateTime.now()}.jpg');
    if (file.existsSync()) {
      file.deleteSync();
      file.create();
    } else {
      file.create();
    }
    await file.writeAsBytes(bytes);
    state.codeFile = file;
    ToastUtils.showToast('生成成功');
    update();
  }

  saveQrCode() async {
    if (!(state.codeFile?.existsSync() ?? false)) {
      showToast('数据为空');
      return;
    }
    Get.dialog(
      defaultDialog(
        title: Strings.save,
        content: '保存到相册',
        sureFunction: () async {
          try {
            await ImageGallerySaver.saveFile(state.codeFile!.path);
            showToast(Strings.saveSuccess);
          } catch (e) {
            showToast(e.toString(), color: Colors.red);
          }
        },
      ),
    );
  }

  onTapCopy() {
    copyText(state.scanValue.value.value ?? '');
  }

  openUrl() async {
    ShareExtend.share(
      state.scanValue.value.value ?? Info.gitHomeUrl,
      'text',
      sharePanelTitle: '选择应用打开或分享',
    );
  }

  shareQrCode() async {
    if (!(state.codeFile?.existsSync() ?? false)) {
      showToast('数据为空');
      return;
    }
    ShareExtend.share(
      state.codeFile!.path,
      'image',
      sharePanelTitle: '选择应用打开或分享',
    );
  }

  onTapSelectLogo() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? response =
          await picker.pickImage(source: ImageSource.gallery);
      if (response == null) return;
      state.logo = File(response.path);
    } catch (e) {
      showToast(e.toString());
    }
    update();
  }

  onTapDeleteLogo() async {
    state.logo = null;
    update();
  }
}
